package com.inspur.dgov.vlbod.controller;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.inspur.dgov.vlbod.entity.DemandBroadcast;
import com.inspur.dgov.vlbod.entity.DemandCollect;
import com.inspur.dgov.vlbod.entity.LiveBroadcast;
import com.inspur.dgov.vlbod.entity.LiveCollect;
import com.inspur.dgov.vlbod.http.DgovResponse;
import com.inspur.dgov.vlbod.secure.token.UserRecord;
import com.inspur.dgov.vlbod.service.*;
import com.inspur.dgov.vlbod.vo.DemandBroadcastVO;
import com.inspur.dgov.vlbod.vo.LiveBroadcastVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;


@Slf4j
    @RestController
    @RequestMapping("/openApi")
    public class OpenApiController {
        @Autowired
        private LiveBroadcastService liveBroadcastService;
        static final String LIVE_THUMBS_UP_KEY = "liveThumbsUpZset@";
        @Autowired
        RedisTemplate redisTemplate;
        @Autowired
        private DemandThumbsUpService demandThumbsUpService;


        @Autowired
        private DemandCollectService demandCollectService;
        @Autowired
        private LiveCollectService liveCollectService;
      /**
         * 直播列表查询
         *
         * @param data：直播列表查询参数（type：类型（1-我的直播，2-我的收藏，3-直播列表），pageNo：页码，pageSize：每页条数，searchContext：查询关键字）
         * @return DgovResponse
         */
        @PostMapping("/live/list")
        public DgovResponse liveList(@RequestHeader String userId, @RequestBody JSONObject data) {
            try {
                // 直播列表类型校验
                String type = data.getString("type");
                if (!StrUtil.equalsAny(type, "1", "2", "3")) {
                    return DgovResponse.fail("请检查直播列表类型");
                }
                data.put("userId", userId);
                // 获取分页条件
                int pageNo = data.getIntValue("pageNo");
                if (0 == pageNo) {
                    pageNo = 1;
                }
                int pageSize = data.getIntValue("pageSize");
                if (0 == pageSize) {
                    pageSize = 10;
                }

                Page<LiveBroadcastVO> page = new Page<>(pageNo, pageSize);
                Page<LiveBroadcastVO> pageList;
                // 我的直播
                if ("1".equals(type)) {
                    pageList = this.liveBroadcastService.queryMyList(page, data);
                } else if ("2".equals(type)) {
                    // 我的收藏
                    pageList = this.liveBroadcastService.queryCollectList(page, data);
                } else {
                    // 直播列表
                    pageList = this.liveBroadcastService.queryList(page, data);
                }
                return DgovResponse.success(pageList);
            } catch (Exception e) {
                log.error("/live/info/list error:" + e.getMessage());
                return DgovResponse.fail("直播列表查询失败");
            }
        }

        /**
         * 获取直播详情信息
         *
         * @param id 直播ID
         * @return
         */
        @GetMapping("/live/info/{id}")
        public DgovResponse info(@PathVariable String id) {
            LiveBroadcast bean = this.liveBroadcastService.getById(id);
            return DgovResponse.success(bean);
        }


        @Autowired
        private DemandBroadcastService demandBroadcastService;

        /**
         * 点播列表查询
         *
         * @param data：点播列表查询参数（type：类型（1-点播列表，2-我的收藏），pageNo：页码，pageSize：每页条数，searchContext：查询关键字）
         * @return DgovResponse
         */
        @PostMapping("/demand/list")
        public DgovResponse demandList(@RequestHeader String userId, @RequestBody JSONObject data) {
            try {
                // 直播列表类型校验
                String type = data.getString("type");
                if (!StrUtil.equalsAny(type, "1", "2")) {
                    return DgovResponse.fail("请检查点播列表类型");
                }
                // 获取当前登录用户ID

                data.put("userId", userId);
                // 获取分页条件
                int pageNo = data.getIntValue("pageNo");
                if (0 == pageNo) {
                    pageNo = 1;
                }
                int pageSize = data.getIntValue("pageSize");
                if (0 == pageSize) {
                    pageSize = 10;
                }

                Page<DemandBroadcastVO> page = new Page<>(pageNo, pageSize);
                Page<DemandBroadcastVO> pageList;
                // 点播
                if ("1".equals(type)) {
                    // 直播列表
                    pageList = this.demandBroadcastService.queryList(page, data);
                } else {
                    // 我的收藏
                    pageList = this.demandBroadcastService.queryCollectList(page, data);
                }
                return DgovResponse.success(pageList);
            } catch (Exception e) {
                log.error("/demand/list error:" + e.getMessage());
                return DgovResponse.fail("点播列表查询失败");
            }
        }

        /**
         * 获取点播信息
         * @param demandId 点播详情
         * @return 结果
         */
        @GetMapping("/demand/info/{id}")
        public DgovResponse getDemandBroadcast(@PathVariable("id") String demandId){
            try {
                DemandBroadcast demandBroadcast = demandBroadcastService.getById(demandId);
                return DgovResponse.success(demandBroadcast);
            }catch (Exception exception){
                log.error("get demand info failed!",exception);
                return DgovResponse.fail("获取点播信息失败");
            }
        }


    /**
     * 统计直播点赞数
     *
     * @param id 直播ID
     * @return
     */
    @GetMapping("/live/up/count/{id}")
    public DgovResponse liveUpCount(HttpServletRequest request, @PathVariable String id) {
        String redisLiveId = LIVE_THUMBS_UP_KEY + id;
        Long count = this.redisTemplate.opsForZSet().size(redisLiveId);
        if (null == count) {
            count = 0L;
        }
        return DgovResponse.success(count);
    }


    /**
     * 检查当前用户是否已点赞
     *
     * @param id 直播ID
     * @return
     */
    @GetMapping("/live/up/check/{id}")
    public DgovResponse upCheck(@RequestHeader String userId, @PathVariable String id) {
        String redisLiveId = LIVE_THUMBS_UP_KEY + id;
        // 获取当前登录用户ID
        Double score = this.redisTemplate.opsForZSet().score(redisLiveId, userId);
        return DgovResponse.success(null != score);
    }

    /**
     * 统计直播收藏数
     *
     * @param id 直播ID
     * @return
     */
    @GetMapping("live/collect/count/{id}")
    public DgovResponse liveCount(@PathVariable String id) {
        LambdaQueryWrapper<LiveCollect> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(LiveCollect::getBroadcastId, id);
        int count = this.liveCollectService.count(queryWrapper);
        return DgovResponse.success(count);
    }
    /**
     * 检查当前用户是否已收藏
     *
     * @param id 直播ID
     * @return
     */
    @GetMapping("/live/collect/check/{id}")
    public DgovResponse liveCollectCheck(@RequestHeader String userId, @PathVariable String id) {
        // 获取当前登录用户ID

        LambdaQueryWrapper<LiveCollect> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(LiveCollect::getUserId, userId);
        queryWrapper.eq(LiveCollect::getBroadcastId, id);
        int count = this.liveCollectService.count(queryWrapper);
        return DgovResponse.success(count > 0);
    }


    /**
     * 根据点播id获取点赞总数
     * @param demandId 点播id
     * @return 总数
     */
    @GetMapping("/demand/up/count/{id}")
    public DgovResponse getDemandUpCount(@PathVariable("id") String demandId){
        try{
            return DgovResponse.success(demandThumbsUpService.getDemandUpCount(demandId));
        }catch (Exception exception){
            log.error("get up count failed",exception);
            return DgovResponse.fail("查询失败");
        }
    }

    /**
     * 检查点赞状态
     * @param demandId 点赞id
     * @return 结果
     */
    @GetMapping("/demand/up/check/{id}")
    public DgovResponse isDemandUp(@RequestHeader String userId, @PathVariable("id") String demandId){
        //获取当前用户
        try{
            return DgovResponse.success(demandThumbsUpService.isUp(demandId,userId));
        }catch (Exception exception){
            log.error("check up failed",exception);
            return DgovResponse.fail("检查点赞失败");
        }

    }

    /**
     * 获取点播收藏总数
     * @param demandId 点播id
     * @return 总数
     */
    @GetMapping("/demand/collect/count/{id}")
    public DgovResponse getCollectCount(@PathVariable("id") String demandId){
        try {
            return DgovResponse.success(demandCollectService.lambdaQuery().eq(DemandCollect::getDemandId,demandId).count());
        }catch (Exception exception){
            log.error("count collect failed",exception);
            return DgovResponse.fail(exception.getMessage());
        }
    }

    @GetMapping("/demand/collect/check/{id}")
    public DgovResponse isCollect(@RequestHeader String userId,@PathVariable("id") String demandId){

        try {
            Integer count = demandCollectService.lambdaQuery().
                    eq(DemandCollect::getUserId, userId).
                    eq(DemandCollect::getDemandId, demandId).count();
            return DgovResponse.success(count > 0);
        }catch (Exception exception){
            log.error("check exist collect failed",exception);
            return DgovResponse.fail(exception.getMessage());
        }
    }






}
